package cn.com.elite;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sfmi.component.chnchannel.chncallcenter.client.ContractClient;
import sfmi.component.chnchannel.chncallcenter.client.CustomerClient;
import sfmi.component.chnchannel.chncallcenter.client.VOCClient;
import sfmi.component.chnchannel.chncallcenter.dto.common.Page;
import sfmi.component.chnchannel.chncallcenter.dto.contract.Contract;
import sfmi.component.chnchannel.chncallcenter.dto.customer.Customer;
import sfmi.component.chnchannel.chncallcenter.dto.enums.ConnectMode;
import sfmi.component.chnchannel.chncallcenter.dto.voc.VOCHistory;
import sfmi.component.chnchannel.chncallcenter.dto.voc.VOCHistory4AutoCall;
import sfmi.component.chnclaim.agentforlegacyclaim.deploy.AgentForLegacyClaimHome;
import sfmi.component.chnclaim.agentforlegacyclaim.deploy.AgentForLegacyClaimRemote;
import sfmi.component.chnclaim.agentforlegacyclaim.dto.CallCenterResult;

public class SanEjbService extends HttpServlet{
	private static final Log log=LogFactory.getLog(SanEjbService.class);
	
	private String getERRO(Exception e){
		String str="";
		try{
            StringWriter sw=new StringWriter();  
            e.printStackTrace(new PrintWriter(sw,true));  
            str=sw.toString(); 	
		}catch(Exception e1){
			str=e.toString();
			log.error("getERRO:"+e1.toString());
		}
		return str;
	}
	private String getAutoCall(String carNo,String caprTelNo,String contorRecgNo){
		String xml="";
		try{
			VOCClient vocClient = new VOCClient(ConnectMode.RealServer);
			Page page = new Page();
			page.setCurrentPage(1);
			page.setRowCntPerPage(10);
			HashMap condition = new HashMap<String, Object>();
			condition.put("carNo", carNo);
			condition.put("caprTelNo", caprTelNo);
			condition.put("contorRecgNo",contorRecgNo);
			page.setCondition(condition);
			page=vocClient.findHistoryList4AutoCall(page);
			List<VOCHistory4AutoCall> list=(List<VOCHistory4AutoCall>)page.getListData();
			if(list!=null&&list.size()>0){
				for(int i=0;i<list.size();i++){
					VOCHistory4AutoCall vOCHistory=(VOCHistory4AutoCall)list.get(i);
					xml=xml+"<VOCHistory>";
					xml=xml+"<CaprRecgName>"+vOCHistory.getCaprRecgName()+"</CaprRecgName>";
					xml=xml+"<ActClerkNm>"+vOCHistory.getActClerkNm()+"</ActClerkNm>";
					xml=xml+"<ActClerkNo>"+vOCHistory.getActClerkNo()+"</ActClerkNo>";
					xml=xml+"<CaprTelAreaNo>"+vOCHistory.getCaprTelAreaNo()+"</CaprTelAreaNo>";
					xml=xml+"<CaprTelNatlNo>"+vOCHistory.getCaprTelNatlNo()+"</CaprTelNatlNo>";
					xml=xml+"<ProcStatCd>"+vOCHistory.getProcStatCd()+"</ProcStatCd>";
					xml=xml+"<ProcStatNm>"+vOCHistory.getProcStatNm()+"</ProcStatNm>";
					xml=xml+"<RcivSeqNum>"+vOCHistory.getRcivSeqNum()+"</RcivSeqNum>";
					xml=xml+"<CaprTelNo>"+vOCHistory.getCaprTelNo()+"</CaprTelNo>";
					xml=xml+"<CaprTelOfcNo>"+vOCHistory.getCaprTelOfcNo()+"</CaprTelOfcNo>";
					xml=xml+"<VocClsCd>"+vOCHistory.getVocClsCd()+"</VocClsCd>";
					xml=xml+"<VocClsNm>"+vOCHistory.getVocClsNm()+"</VocClsNm>";
					xml=xml+"<CaprTelSerialNo>"+vOCHistory.getCaprTelSerialNo()+"</CaprTelSerialNo>";
					xml=xml+"<CarNo>"+vOCHistory.getCarNo()+"</CarNo>";
					xml=xml+"<CloseDttm>"+vOCHistory.getCloseDttm()+"</CloseDttm>";
					xml=xml+"<ContorRecgNo>"+vOCHistory.getContorRecgNo()+"</ContorRecgNo>";
					xml=xml+"<CvapClsNm>"+vOCHistory.getCvapClsNm()+"</CvapClsNm>";
					xml=xml+"<CvapClsCd>"+vOCHistory.getCvapClsCd()+"</CvapClsCd>";
					xml=xml+"<FkPlcyNo>"+vOCHistory.getFkPlcyNo()+"</FkPlcyNo>";
					xml=xml+"<RcivDttm>"+vOCHistory.getRcivDttm()+"</RcivDttm>";
					xml=xml+"<RelClerkDeptCd>"+vOCHistory.getRelClerkDeptCd()+"</RelClerkDeptCd>";
					xml=xml+"<RelClerkDeptNm>"+vOCHistory.getRelClerkDeptNm()+"</RelClerkDeptNm>";
					xml=xml+"</VOCHistory>";   
				}
			}else{
				return "<null>null</null>";
			}
			
		}catch(Exception e){
			log.error(getERRO(e));
			return "<wrong>"+getERRO(e)+"</wrong>";
		}
		return xml;
	}
	private String getCustomer(String ptyId,String ptyCls,String customerName,String customerTypeId,String customerId,String provinceId,String address,String zipcode,String cityId,String tel,String companyName,String companyProvinceId,String companyAddress,String companyZipcode,String companyCityId,String companyTel,String mobile,String fax,String email,String gender,String birthday,String position,String inputClerk){
		String returnxml="";
		try{
	    	CustomerClient commonClient=new CustomerClient(ConnectMode.RealServer);   
	    	Customer customer=new Customer();
	    	
	    	customer.setPtyId(ptyId);
	    	customer.setPtyCls(ptyCls);
	    	customer.setCustomerName(customerName);
	    	customer.setCustomerTypeId(customerTypeId);
	    	customer.setCustomerId(customerId);
	    	customer.setProvinceId(provinceId);
	    	customer.setAddress(address);
	    	customer.setZipcode(zipcode);
	    	customer.setCityId(cityId);
	    	customer.setTel(tel);
	    	customer.setCompanyName(companyName);
	    	customer.setCompanyProvinceId(companyProvinceId);
	    	customer.setCompanyAddress(companyAddress);
	    	customer.setCompanyZipcode(companyZipcode);
	    	customer.setCompanyCityId(companyCityId);
	    	customer.setCompanyTel(companyTel);
	    	customer.setMobile(mobile);
	    	customer.setFax(fax);
	    	customer.setEmail(email);
	    	customer.setGender(gender);
	    	customer.setBirthday(birthday);
	    	customer.setPosition(position);
	    	customer.setInputClerk(inputClerk);
	    	commonClient.updateCustomer(customer);
	    	
//	    	String t3url="t3://109.101.108.51:33001";
//			java.util.Properties p=new java.util.Properties();
//			p.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
//			p.put(Context.PROVIDER_URL,t3url);
//			Context ctx=new InitialContext(p);
//			Object h=ctx.lookup("ejb/AgentForLegacyClaim");
//			AgentForLegacyClaimHome home=(AgentForLegacyClaimHome)PortableRemoteObject.narrow(h,AgentForLegacyClaimHome.class);
//			AgentForLegacyClaimRemote AgentForLegacyClaimRemote=home.create();
//			List<CallCenterResult> result=AgentForLegacyClaimRemote.getClaimInfoForCallCenterByPtyId(ptyId);
//			if(result==null){
//				returnxml="<result>fail</result>";
//			}else{
//				returnxml="<result>success</result>";
//			}    
			returnxml="<result>success</result>";
		}catch(Exception e){
			log.error(getERRO(e));
			return "<wrong>"+getERRO(e)+"</wrong>";
		}
		return returnxml;
	}
	private String getVOC(String guid){
		String xml="";
		try{
			VOCClient vocClient=new VOCClient(ConnectMode.RealServer); 
			List<VOCHistory> list=vocClient.findHistoryList(guid);
			if(list!=null&&list.size()>0){
				for(int i=0;i<list.size();i++){
					VOCHistory vOCHistory=(VOCHistory)list.get(i);
					xml=xml+"<VOCHistory>";
					xml=xml+"<CaprRecgName>"+vOCHistory.getCaprRecgName()+"</CaprRecgName>";
					xml=xml+"<CaprRecgNo>"+vOCHistory.getCaprRecgNo()+"</CaprRecgNo>";
					xml=xml+"<CaprRecgNoTypeCd>"+vOCHistory.getCaprRecgNoTypeCd()+"</CaprRecgNoTypeCd>";
					xml=xml+"<ChnlCd>"+vOCHistory.getChnlCd()+"</ChnlCd>";
					xml=xml+"<ChnlNm>"+vOCHistory.getChnlNm()+"</ChnlNm>";
					xml=xml+"<ProcStatCd>"+vOCHistory.getProcStatCd()+"</ProcStatCd>";
					xml=xml+"<ProcStatNm>"+vOCHistory.getProcStatNm()+"</ProcStatNm>";
					xml=xml+"<RcivSeqNum>"+vOCHistory.getRcivSeqNum()+"</RcivSeqNum>";
					xml=xml+"<RelClerkNm>"+vOCHistory.getRelClerkNm()+"</RelClerkNm>";
					xml=xml+"<RelClerkNo>"+vOCHistory.getRelClerkNo()+"</RelClerkNo>";
					xml=xml+"<VocClsCd>"+vOCHistory.getVocClsCd()+"</VocClsCd>";
					xml=xml+"<VocClsNm>"+vOCHistory.getVocClsNm()+"</VocClsNm>";
					xml=xml+"<VocConts>"+vOCHistory.getVocConts()+"</VocConts>";
					xml=xml+"<VocTitle>"+vOCHistory.getVocTitle()+"</VocTitle>";
					xml=xml+"</VOCHistory>";
				}
			}else{
				return "<null>null</null>";
			}
		}catch(Exception e){
			log.error(getERRO(e));
			return "<wrong>"+getERRO(e)+"</wrong>";
		    
		}
		return xml;
	}
	private String getContract(String guid){
		String xml="";
		try{
			ContractClient contractClient=new ContractClient(ConnectMode.RealServer);
			List<Contract> contractList=contractClient.findInsuranceList(guid);
			if(contractList!=null&&contractList.size()>0){
				for(int i=0;i<contractList.size();i++){
					Contract contract=(Contract)contractList.get(i);
					xml=xml+"<Contract>";
					xml=xml+"<Currency>"+contract.getCurrency()+"</Currency>";
					xml=xml+"<InsuredNo>"+contract.getInsuredNo()+"</InsuredNo>";
					xml=xml+"<PolicyEndDate>"+contract.getPolicyEndDate()+"</PolicyEndDate>";
					xml=xml+"<PolicyNo>"+contract.getPolicyNo()+"</PolicyNo>";
					xml=xml+"<PolicyStartDate>"+contract.getPolicyStartDate()+"</PolicyStartDate>";
					xml=xml+"<Premium>"+contract.getPremium()+"</Premium>";
					xml=xml+"<TotalSumInsured>"+contract.getTotalSumInsured()+"</TotalSumInsured>";
					xml=xml+"<WrittenDate>"+contract.getWrittenDate()+"</WrittenDate>";
					xml=xml+"<Insured_Email>"+contract.getInsured().getEmail()+"</Insured_Email>";
					
					xml=xml+"<Insured_EnglishName>"+contract.getInsured().getEnglishName()+"</Insured_EnglishName>";
					
					xml=xml+"<Insured_Id>"+contract.getInsured().getId()+"</Insured_Id>";
					xml=xml+"<Insured_MobileNo>"+contract. getInsured().getMobileNo()+"</Insured_MobileNo>";
					xml=xml+"<Insured_Name>"+contract.getInsured().getName()+"</Insured_Name>";
					xml=xml+"<Insured_No>"+contract.getInsured().getNo()+"</Insured_No>";
					xml=xml+"<Insured_PhoneNo>"+contract.getInsured().getPhoneNo()+"</Insured_PhoneNo>";
					
					xml=xml+"<Product_EnglishName>"+contract.getProduct().getEnglishName()+"</Product_EnglishName>";
					xml=xml+"<Product_Name>"+contract.getProduct().getName()+"</Product_Name>";
					
					xml=xml+"<PolicyStatus_Code>"+contract.getPolicyStatus().getCode()+"</PolicyStatus_Code>";
					xml=xml+"<PolicyStatus_Detail>"+contract.getPolicyStatus().getDetail()+"</PolicyStatus_Detail>";
					xml=xml+"<PolicyStatus_EnglishName>"+contract.getPolicyStatus().getEnglishName()+"</PolicyStatus_EnglishName>";
					xml=xml+"<PolicyStatus_Name>"+contract.getPolicyStatus().getName()+"</PolicyStatus_Name>";
					
					xml=xml+"<Policyholder_Email>"+contract.getPolicyholder().getEmail()+"</Policyholder_Email>";
					xml=xml+"<Policyholder_EnglishName>"+contract.getPolicyholder().getEnglishName()+"</Policyholder_EnglishName>";
					xml=xml+"<Policyholder_Id>"+contract.getPolicyholder().getId()+"</Policyholder_Id>";
					xml=xml+"<Policyholder_MobileNo>"+contract.getPolicyholder().getMobileNo()+"</Policyholder_MobileNo>";
					xml=xml+"<Policyholder_Name>"+contract.getPolicyholder().getName()+"</Policyholder_Name>";
					xml=xml+"<Policyholder_No>"+contract.getPolicyholder().getNo()+"</Policyholder_No>";

					xml=xml+"<MarketingStaff_Email>"+contract.getMarketingStaff().getEmail()+"</MarketingStaff_Email>";
					xml=xml+"<MarketingStaff_EnglishName>"+contract.getMarketingStaff().getEnglishName()+"</MarketingStaff_EnglishName>";
					xml=xml+"<MarketingStaff_Id>"+contract.getMarketingStaff().getId()+"</MarketingStaff_Id>";
					xml=xml+"<MarketingStaff_MobileNo>"+contract.getMarketingStaff().getMobileNo()+"</MarketingStaff_MobileNo>";
					xml=xml+"<MarketingStaff_Name>"+contract.getMarketingStaff().getName()+"</MarketingStaff_Name>";
					xml=xml+"<MarketingStaff_No>"+contract.getMarketingStaff().getNo()+"</MarketingStaff_No>";
					xml=xml+"<MarketingStaff_PhoneNo>"+contract.getMarketingStaff().getPhoneNo()+"</MarketingStaff_PhoneNo>";
					xml=xml+"</Contract>";
				}
			}else{
				return "<null>null</null>";
			}
		}catch(Exception e){
			log.error(getERRO(e));
			return "<wrong>"+getERRO(e)+"</wrong>";
		}
//		xml=xml.replace("&","");
//		xml=xml.replace("，","");
//		xml=xml.replace(".","");
		//xml=xml.replace(" ","");
		return xml;
	}
	private String getAgentClaim(String guid){
		String xml="";
		try{
			String t3url="t3://109.101.108.51:33001";
			java.util.Properties p=new java.util.Properties();
			p.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
			p.put(Context.PROVIDER_URL,t3url);
			Context ctx=new InitialContext(p);
			Object h=ctx.lookup("ejb/AgentForLegacyClaim");
			AgentForLegacyClaimHome home=(AgentForLegacyClaimHome)PortableRemoteObject.narrow(h,AgentForLegacyClaimHome.class);
			AgentForLegacyClaimRemote AgentForLegacyClaimRemote=home.create();
			List<CallCenterResult> result=AgentForLegacyClaimRemote.getClaimInfoForCallCenter(guid);
			if(result!=null&&result.size()>0){
				Iterator iterator=result.iterator();
				while(iterator.hasNext()){ 
					CallCenterResult callCenterResult=(CallCenterResult) iterator.next();
					xml=xml+"<CallCenterResult>";
					xml=xml+"<AcceptanceNo>"+callCenterResult.getAcceptanceNo()+"</AcceptanceNo>";
					xml=xml+"<ClaimNo>"+callCenterResult.getClaimNo()+"</ClaimNo>";
					xml=xml+"<PlcyNo>"+callCenterResult.getPlcyNo()+"</PlcyNo>";
					xml=xml+"<PolicyholderName>"+callCenterResult.getPolicyholderName()+"</PolicyholderName>";
					xml=xml+"<InsuredName>"+callCenterResult.getInsuredName()+"</InsuredName>";
					xml=xml+"<ProductName>"+callCenterResult.getProductName()+"</ProductName>";
					xml=xml+"<DateOfLoss>"+callCenterResult.getDateOfLoss()+"</DateOfLoss>";
					xml=xml+"<LossDescription>"+callCenterResult.getLossDescription()+"</LossDescription>";
					xml=xml+"<AcceptanceStaffName>"+callCenterResult.getAcceptanceStaffName()+"</AcceptanceStaffName>";
					xml=xml+"<AdjusterName>"+callCenterResult.getAdjusterName()+"</AdjusterName>";
					xml=xml+"</CallCenterResult>";
				}
			}else{
				return "<null>null</null>";
			}
		}catch(Exception e){
			log.error(getERRO(e));
			return "<wrong>"+getERRO(e)+"</wrong>";
		}
		return xml;
	}
	private String getString(Object obj){
		if(obj==null){
			return "";
		}else{
			return obj.toString();
		}
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException{
		 request.setCharacterEncoding("UTF-8");
		 String type=request.getParameter("type");
		 log.info("type:"+type);
		 String guid=request.getParameter("guid");
		 log.info("guid:"+guid);
		 
		 String ptyId=request.getParameter("ptyId");
		 log.info("ptyId:"+ptyId);
	     String ptyCls=request.getParameter("ptyCls");
	     log.info("ptyCls:"+ptyCls);
	     
	     String customerName=request.getParameter("customerName");
	     if(customerName!=null){
	    	 customerName=URLDecoder.decode(customerName,"UTF-8");
//	    	 customerName=new String(request.getParameter("customerName").getBytes("ISO8859-1"));
		     log.info("customerName:"+customerName);
	     }
	     
	     String customerTypeId=request.getParameter("customerTypeId");
	     log.info("customerTypeId:"+customerTypeId);
	     String customerId=request.getParameter("customerId");
	     log.info("customerId:"+customerId);
	     String provinceId=request.getParameter("provinceId");
	     log.info("provinceId:"+provinceId);
	     
	     String address=request.getParameter("address");
	     if(address!=null){
	    	 address=URLDecoder.decode(address,"UTF-8");
//	    	 address=new String(request.getParameter("address").getBytes("ISO8859-1"));
		     log.info("address:"+address);
	     }
	     
	     String zipcode=request.getParameter("zipcode");
	     log.info("zipcode:"+zipcode);
	     String cityId=request.getParameter("cityId");
	     log.info("cityId:"+cityId);
	     String tel=request.getParameter("tel");
	     log.info("tel:"+tel);
	     String companyName=request.getParameter("companyName");
	     if(companyName!=null){
	    	 companyName=URLDecoder.decode(companyName,"UTF-8");
//	    	 companyName=new String(request.getParameter("companyName").getBytes("ISO8859-1"));
		     log.info("companyAddress:"+companyName);
	     }
	     
	     String companyProvinceId=request.getParameter("companyProvinceId");
	     log.info("companyProvinceId:"+companyProvinceId);
	     
	     String companyAddress=request.getParameter("companyAddress");
	     if(companyAddress!=null){
	    	 companyAddress=URLDecoder.decode(companyAddress,"UTF-8");
//	    	 companyAddress=new String(request.getParameter("companyAddress").getBytes("ISO8859-1"));
		     log.info("companyAddress:"+companyAddress);
	     }
	     
	     String companyZipcode=request.getParameter("companyZipcode");
	     log.info("companyZipcode:"+companyZipcode);
	     String companyCityId=request.getParameter("companyCityId");
	     log.info("companyCityId:"+companyCityId);
	     String companyTel=request.getParameter("companyTel");
	     log.info("companyTel:"+companyTel);
	     String mobile=request.getParameter("mobile");
	     log.info("mobile:"+mobile);
	     String fax=request.getParameter("fax");
	     log.info("fax:"+fax);
	     String email=request.getParameter("email");
	     log.info("email:"+email);
	     String gender=request.getParameter("gender");
	     log.info("gender:"+gender);
	     String birthday=request.getParameter("birthday");
	     log.info("birthday:"+birthday);
	     String position=request.getParameter("position");
	     log.info("position:"+position);
	     String inputClerk=request.getParameter("inputClerk");
	     log.info("inputClerk:"+inputClerk);
	     
	     String carNo=request.getParameter("carNo");
	     if(carNo!=null){
	    	 carNo=URLDecoder.decode(carNo,"UTF-8");
		     log.info("carNo:"+carNo); 
	     }	    	 
	     String caprTelNo=request.getParameter("caprTelNo");
	     log.info("caprTelNo:"+caprTelNo);
	     String contorRecgNo=request.getParameter("contorRecgNo");
	     log.info("contorRecgNo:"+contorRecgNo);
	     
		 String xml="";
		 if(type.equals("VOCClient")){
			 xml=getVOC(guid);
		 }else if(type.equals("Contract")){
			 xml=getContract(guid);
		 }else if(type.equals("AgentClaim")){
			 xml=getAgentClaim(guid); 
		 }else if(type.equals("Customer")){
			 xml=getCustomer(ptyId,ptyCls,customerName,customerTypeId,customerId,provinceId,address,zipcode,cityId,tel,companyName,companyProvinceId,companyAddress,companyZipcode,companyCityId,companyTel,mobile,fax,email,gender,birthday,position,inputClerk);
		 }else if(type.equals("getAutoCall")){
			 xml=getAutoCall(carNo,caprTelNo,contorRecgNo);
		 }
		 xml="<?xml version='1.0' encoding='utf-8'?><root><value>"+xml+"</value></root>";
		 request.setCharacterEncoding("UTF-8");
	     response.setContentType("text/html;charset=utf-8;");
	     PrintWriter out = response.getWriter();
	     log.info("xml:"+xml);
	     out.print(xml);
	 }

	 public void doGet(HttpServletRequest request, HttpServletResponse response)
	 throws ServletException, IOException{
		 this.doPost(request, response);
	 }
}
